<template>
  <NavBar title="旅游助手" />

  <div class="content">
    <var-card
      class="item"
      :class="item.type === 'user' ? 'user' : ''"
      v-for="(item, index) in infoStore.chatList"
      :key="index"
      :description="item.content"
    />
    <var-loading v-if="loading" type="wave" size="small" />
    <var-link
      v-else
      v-show="infoStore.chatList.length"
      @click="infoStore.chatList = []"
      type="primary"
      underline="none"
      >清空</var-link
    >
    <div style="height: 200px" ref="bottomRef"></div>
  </div>

  <div class="bottom">
    <var-input
      variant="outlined"
      placeholder="与旅游助手交谈"
      size="small"
      v-model="text"
      @keyup.enter="send"
    />
    <i @click="send" class="iconfont icon-a-youjiantouzhixiangyoujiantou"></i>
  </div>
</template>

<script setup lang="ts">
import NavBar from '@/components/NavBar.vue'
import axios from 'axios'
import { useInfoStore } from '@/store/info'
import { debounce } from '@/utils'

const infoStore = useInfoStore()

const text = ref('')
const loading = ref(false)
const bottomRef = ref(null)

const smoothScroll = () => {
  bottomRef.value.scrollIntoView({ behavior: 'smooth' })
}

onMounted(() => {
  smoothScroll()
})
watch(infoStore.chatList, () => {
  smoothScroll()
})

const formatText = text => {
  const regex = /(\*\* \*\*|\* \* \*)/g
  return text.replace(regex, '\n').replace(/\*\*/g, '').replace(/\*/g, '\n')
}

const send = debounce(async () => {
  if (!text.value.trim()) return
  infoStore.chatList.push({
    type: 'user',
    content: text.value
  })
  loading.value = true

  // const { data: res } = await axios.get('/chat', {
  //   params: {
  //     key: 'free',
  //     appid: 0,
  //     msg: text.value
  //   }
  // })

  const { data: res } = await axios.post(`/chat?text=${text.value}`)

  text.value = ''
  loading.value = false
  infoStore.chatList.push({
    type: 'gpt',
    // content: res.content
    content: formatText(res)
  })
})
</script>

<style scoped lang="scss">
.content {
  padding: 10px 0;
  padding-bottom: 60px;
  box-sizing: border-box;
  overflow-y: auto;
  height: calc(100vh - 120px);

  .var-link {
    position: relative;
    left: 50%;
    transform: translateX(-50%);
  }

  .item {
    margin-bottom: 10px;
  }

  .user {
    :deep(.var-card__floater) {
      background-color: #f7f7f7;
      text-align: right;
    }
  }
}

.bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  display: flex;
  align-items: center;
  height: 60px;
  padding: 10px;
  background-color: #fff;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  box-sizing: border-box;

  .var-input {
    flex: 1;
    margin-right: 5px;
  }
}

:deep(.var-card__description) {
  margin-top: 0;
  padding-top: 16px;
}
</style>
